﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace yaip.Filters.PixelPoint {
    public class Invert : PixelPointFilter {
        
        
        public bool apply(Bitmap bitmap) {
            int height = bitmap.Height;
            int width = bitmap.Width;
            BitmapData bmData = bitmap.LockBits(
                new Rectangle(0, 0, width, height),
                ImageLockMode.ReadWrite, bitmap.PixelFormat);
                
                //PixelFormat.Format24bppRgb);

            // How wide a line is
            int stride = bmData.Stride;
            // Pointer to the data  
            System.IntPtr Scan0 = bmData.Scan0;

            //because of the pointers (compiling flag: /unsafe)
            unsafe {
                byte* ptr = (byte*)(void*)Scan0;

                // We need the offset to skip the existent padding
                // in each row (bitmaps are word align)
                int nOffset = stride - width * 3;
                int nWidth = width * 3;

                for (int y = 0; y < height; ++y) {
                    for (int x = 0; x < nWidth; ++x) {
                        ptr[0] = (byte)(255 - ptr[0]);
                        ++ptr;
                    }
                    ptr += nOffset;
                }
            }
            bitmap.UnlockBits(bmData);
            return true;
        }
    }
}
